/**
 * 
 */
package com.acme.bankapp.service.bank;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.CheckingAccount;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.bankapp.domain.bank.SavingAccount;

/**
 * Class for load feed file
 * @author Vasilyev Anton
 *
 */
public class BankDataLoaderService {
	public Bank loadFeed(String feedName) throws Exception {
		String curString;
		Bank bank = new Bank();
		Client client = null;
		try (
			BufferedReader reader = new BufferedReader(new FileReader(feedName));){
			while ( (curString = reader.readLine()) != null) {
				client = parseFeed(curString);
				bank.addClient(client);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return bank;
	}
	
	private Client parseFeed(String string) throws Exception {
		double overdraft = 0;
		double balance = 0;
		String accType = null;
		String name = null;
		Gender gender = null;
		Account acc;
		
		String [] tokens = string.split(";");
		for (String token : tokens) {
			String type = token.split("=")[0];
			String value = token.split("=")[1];
			switch(type) {
			case "accounttype" :
				accType = value;
				break;
			case "balance" :
				balance = Double.parseDouble(value);
				break;
			case "overdraft":
				overdraft = Double.parseDouble(value);
				break;
			case "name":
				name = value;
				break;
			case "gender":
				switch(value) {
				case "f":
					gender = Gender.FEMALE;
					break;
				case "m":
					gender = Gender.MALE;
					break;
				default:
					throw new Exception("Wrong value");
				}
				break;
			}
		}
		
		switch(accType) {
		case "c":
			acc = new CheckingAccount(balance, overdraft);
			break;
		case "s":
			acc = new SavingAccount(balance);
			break;
		default:
			throw new Exception("Wrong value");
		
		}
		return new Client(gender, name, acc);
	}

}
